package com.maxtech.common.gps;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;

import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class Utils {
	private static final String TAG = "Utils";
//	private static final boolean DEBUG = AppConfig.DEBUG;
	public static void log(String str)
	{
		LogUtil.e("Utils", str);
	}		
	public static String url = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true";
    public static boolean haveInternet(Context context)  				// is Internet available
    {
        NetworkInfo info=(NetworkInfo)((ConnectivityManager) 
        				context.getSystemService(Context.CONNECTIVITY_SERVICE)
        				).getActiveNetworkInfo();  

        if(info==null || !info.isConnected())  
            return false;  
        
        if(info.isRoaming() || info.isAvailable())  
            return true;  
        
        return false; 
    }

    //	获取屏幕分辨率
	public static void getMatrix(Activity activity) {
		// TODO Auto-generated method stub
		DisplayMetrics metrics = new DisplayMetrics(); 

		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); 
		
		LogUtil.e(TAG, ""+metrics.heightPixels);
		LogUtil.e(TAG, ""+metrics.widthPixels);
	}
	//Check Mobile State
    public static boolean CheckMobileState(Context context)
    {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        
        if(mobile != State.CONNECTED)
            return false;
        
        return true;
    }
    
	//Check Wifi State
    public static boolean CheckWifiState(Context context)
    {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(
                Context.CONNECTIVITY_SERVICE);

        State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

        if(wifi != State.CONNECTED)
            return false;
        
        return true;        
    }    
    
	//Check network
    public static void CheckNetworkState(Context context)
    {
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        //如果3G、wifi、2G等网络状态是连接的，则退出，否则显示提示信息进入网络设置界面
        if(mobile == State.CONNECTED||mobile==State.CONNECTING)
        return;
        if(wifi == State.CONNECTED||wifi==State.CONNECTING)
        return;
//        showTips(context);
    }
    
    public static boolean isNetworkAvailable_old(Context context)  		// another way to judge whether net is available
    {
//		Context context = getApplicationContext();  
    	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  

    	if (connectivity == null) {  
    		return false;
    	} else {
    		NetworkInfo[] info = connectivity.getAllNetworkInfo();  
    	    if (info != null) {  
    	    	for (int i = 0; i < info.length; i++) {  
    	        	if (info[i].getState() == NetworkInfo.State.CONNECTED) 
    	        		return true; 
	    	 	}  
	    	}  
		}  
		return false;  
	}
    /** 
     * 检测网络连接是否可用 
     * @param context 
     * @return true 可用; false 不可用 
     */  
    public static boolean isNetworkAvailable(Context context) {  
        ConnectivityManager cm =   
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        if(cm == null) {  
            return false;  
        }  
        NetworkInfo[] netinfo = cm.getAllNetworkInfo();  
        if(netinfo == null) {  
            return false;  
        }  
        for (int i = 0; i < netinfo.length; i++) {  
            if(netinfo[i].isConnected()) {  
                return true;  
            }  
        }  
        return false;  
    }  
    
	private static final int TIME_OUT = AppConfig.TIME_OUT;
	private static final String URL = AppConfig.URL;
	private static final String CHARSET = AppConfig.CHARSET;
	private static final int CLIENT_BUFFER_SIZE = AppConfig.CLIENT_BUFFER_SIZE;
	
	public static synchronized String getContent(String url) throws Exception {
		try{
			StringBuilder sb = new StringBuilder();
			HttpClient client = new DefaultHttpClient();
			HttpParams httpParams = client.getParams();

			String final_url = url;
			LogUtil.e(TAG, "url:" + final_url);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, TIME_OUT);	// 设置网络超时参数
			HttpConnectionParams.setSoTimeout(httpParams, TIME_OUT);
			HttpResponse response = client.execute(new HttpPost(final_url));
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						entity.getContent(), CHARSET), CLIENT_BUFFER_SIZE);
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					HttpConnectionParams.setSoTimeout(httpParams, TIME_OUT);
				}
				reader.close();
			}
			
			String result = sb.toString();
			LogUtil.e(TAG, "getContent():" + result);
			
			return result;	
		} 
		
		catch (Exception e){
			LogUtil.e(TAG, "", e);
			return null;
		}	
	}
	public static boolean isGoogleMapSupported()						// test if Google Map add-on is supported
	{
		try {  
		    Class.forName("com.google.android.maps.MapActivity");  
		    return true;
		} catch (Exception e) {
		    return false;  
		}  
	}

  //Get the Location by GPS or WIFI   
  public static Location getLocation(Context context) {  
      LocationManager locMan = (LocationManager) context  
              .getSystemService(Context.LOCATION_SERVICE);  
      Location location = locMan  
              .getLastKnownLocation(LocationManager.GPS_PROVIDER);  
      if (location == null) {  
          location = locMan  
                  .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  
      }  
      return location;  
  }  
  //通过Location获取GeoPoint   
   public static GeoPoint getGeoByLocation(Location location) {  
       GeoPoint gp = null;  
       try {  
           if (location != null) {  
               double geoLatitude = location.getLatitude() * 1E6;  
               double geoLongitude = location.getLongitude() * 1E6;  
               gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);  
           }  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       return gp;  
   }  
   //通过GeoPoint来获取Address   
   public static Address getAddressbyGeoPoint(Context cntext, GeoPoint gp) {  
       Address result = null;  
       try {  
           if (gp != null) {  
               Geocoder gc = new Geocoder(cntext, Locale.CHINA);  
                
               double geoLatitude = (int) gp.getLatitudeE6() / 1E6;  
               double geoLongitude = (int) gp.getLongitudeE6() / 1E6;  
                 
               List<Address> lstAddress = gc.getFromLocation(geoLatitude,  
                       geoLongitude, 1);  
               if (lstAddress.size() > 0) {  
                   result = lstAddress.get(0);  
               }  
           }  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       return result;  
   }   
	public static byte[] getImage(String urlpath) throws Exception {
		LogUtil.d(TAG, "urlpath:"+urlpath);
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(6 * 1000);
		// 别超过10秒。
		if(conn.getResponseCode()==200){
			InputStream inputStream=conn.getInputStream();
			return readStream(inputStream);
		}
		return null;
	}
	
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outstream=new ByteArrayOutputStream();
		byte[] buffer=new byte[1024];
		int len=-1;
		while((len=inStream.read(buffer)) !=-1){
			outstream.write(buffer, 0, len);
		}
		outstream.close();
		inStream.close();
		
		return outstream.toByteArray();
	}


	public static String getHtml(String path,String encoding) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(6 * 1000);
		// 别超过10秒。
		LogUtil.d(TAG, ""+conn.getResponseCode());
		if(conn.getResponseCode()==200){
			InputStream inputStream=conn.getInputStream();
			byte[] data=readStream(inputStream);
			return new String(data,encoding);
		}
		return null;
	}

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    	if(bitmap == null)
    		return null;
    	
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

//        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = 20;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
//        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
    
    public static String getFormattedDate(){

		long l = System.currentTimeMillis();			
		SimpleDateFormat sdf = new SimpleDateFormat("",Locale.SIMPLIFIED_CHINESE); 
		
		sdf.applyPattern("yyyyMMddhhmmss"); 			
		String timeStr = sdf.format(l); 
		
		return timeStr;
    }
    
	public static void Toast(Context context, String str) {
		// TODO Auto-generated method stub
		Toast.makeText(context, str, Toast.LENGTH_LONG).show();
		
//		Toast toast = new Toast(ctx);
//		toast.setGravity(Gravity.CENTER, 0, 0);
//		toast.makeText(ctx, "" + str, Toast.LENGTH_LONG).show();
	}
	
	
	//	SD card operations
	//	**********************************************************************************************	
	public static String getSDPath(){
//        LogUtil.e(TAG, "getSDPath()");
		File SDdir = null;
        try{
            
            boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
            if(sdCardExist)
                    SDdir = Environment.getExternalStorageDirectory();
            
            if(SDdir==null)
            	return null;
            
//            LogUtil.e(TAG, "SDdir.toString():" + SDdir.toString());
	        return SDdir.toString();
        }catch(Exception e){
			return null;
		}
	}
	public static boolean createSDCardDir(String dir){
        LogUtil.e(TAG, "createSDCardDir()");
		try{			
	        if(getSDPath()==null){
	            return false;
	        }
	        else{
	            if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
	            	// 创建一个文件夹对象，赋值为外部存储器的目录
//	            	File sdcardDir =Environment.getExternalStorageDirectory();
	            	//得到一个路径，内容是sdcard的文件夹路径和名字
	            	String newPath = getSDPath() + dir;
	            	File path1 = new File(newPath);
	            	if (!path1.exists()) {
	            		//若不存在，创建目录，可以在应用启动的时候创建
	            		if(!path1.mkdirs())
	            		{
		            		LogUtil.d(TAG, "create path error");
	            			return false;
	            		}
	            		LogUtil.d(TAG, "create path ok,path:"+newPath);
	            	}
	            	return true;
	            }
	            else{
	            	LogUtil.d(TAG, "false");
	            	return false;
	            }
	        }
		}
		catch(Exception e){
			return false;
		}
    }
    public static Bitmap getBmpFromSDcard(String dir) { 
    	try{
        	if(dir == null) 
        		return null; 
        	
        	if(dir.equals("")) 
        		return null; 
        	
        	Bitmap bitmap = null;
        	bitmap = BitmapFactory.decodeFile(dir); 
        	return bitmap;    		
    	}
        catch (Exception e){
	    	return null;
	    }
    } 
    public static Uri addImageAsCamera(ContentResolver cr, Bitmap bitmap) {   

    	long dateTaken = System.currentTimeMillis();   

		String name = createName(dateTaken) + ".jpg";   

		String uriStr = MediaStore.Images.Media.insertImage(cr, bitmap, name,   
			null);

		if(uriStr==null)
			return null;
		
		return Uri.parse(uriStr);  
	}   

	private static String createName(long dateTaken) {  
		return DateFormat.format("yyyy-MM-dd_kk.mm.ss", dateTaken).toString();   
	}  

	private static final String APPLICATION_NAME = "PATOM";   
	private static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;   
	private static final String PATH = Environment.getExternalStorageDirectory().toString() + "/" + APPLICATION_NAME;   
	
	public static Uri addImageAsApplication(ContentResolver cr, Bitmap bitmap, String filename) {   
	    long dateTaken = System.currentTimeMillis();   
//	    String name = createName(dateTaken) + ".jpg";  
	    String name = filename + ".jpg";   
	    
	    return addImageAsApplication(cr, name, dateTaken, PATH, name, bitmap, null);   
	}   
	public static Uri addImageAsApplication(ContentResolver cr, String name,   
	        long dateTaken, String directory,   
	         String filename, Bitmap source, byte[] jpegData) {   
	   
	     OutputStream outputStream = null;   
	     String filePath = directory + "/" + filename;   
	    try {   
	         File dir = new File(directory);   
	        if (!dir.exists()) {   
	             dir.mkdirs();   
	             LogUtil.e(TAG, dir.toString() + " create");   
	         }   
	         File file = new File(directory, filename);   
	        if (file.createNewFile()) {   
	             outputStream = new FileOutputStream(file);   
	            if (source != null) {   
	                 source.compress(CompressFormat.JPEG, 75, outputStream);   
	             } else {   
	                 outputStream.write(jpegData);   
	             }   
	         }   
	   
	     } catch (FileNotFoundException e) {   
	         LogUtil.ex(TAG, "", e);
	        return null;   
	     } catch (IOException e) {   
	         LogUtil.ex(TAG, "", e);
	        return null;   
	     } finally {   
	        if (outputStream != null) {   
	            try {   
	                 outputStream.close();   
	             } catch (Throwable t) {   
	             }   
	         }   
	     }   
	       
	     ContentValues values = new ContentValues(7);   
	     values.put(Images.Media.TITLE, name);   
	     values.put(Images.Media.DISPLAY_NAME, filename);   
	     values.put(Images.Media.DATE_TAKEN, dateTaken);   
	     values.put(Images.Media.MIME_TYPE, "image/jpeg");   
	     values.put(Images.Media.DATA, filePath);   
	     return cr.insert(IMAGE_URI, values);   
	}   
//	public static void saveMyBitmap(String bitName,int percent) throws IOException {
//        
//        Bitmap bmp = drawable2Bitmap(picView.getDrawable());//这里的drawable2Bitmap方法是我把ImageView中 的drawable转化成bitmap，当然实验的时候可以自己创建bitmap
//        File f = new File(newPath + bitName + ".jpg");
//        f.createNewFile();
//        FileOutputStream fOut = null;
//        try {
//            fOut = new FileOutputStream(f);        
//            } catch (FileNotFoundException e) {        
//            LogUtil.ex(TAG, "", e);
//	    }
//	    bmp.compress(Bitmap.CompressFormat.JPEG, percent, fOut);
//	    try {
//	            fOut.flush();
//	    } catch (IOException e) {
//	            LogUtil.ex(TAG, "", e);
//	    }
//	    try {
//	            fOut.close();
//	    } catch (IOException e) {
//	            LogUtil.ex(TAG, "", e);
//	    }
//	}
	public static Bitmap drawable2Bitmap(Drawable d){
        int width=d.getIntrinsicWidth();
        int height=d.getIntrinsicHeight();
        Bitmap.Config config=d.getOpacity()!=PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
        Bitmap bitmap=Bitmap.createBitmap(width,height,config);
        Canvas canvas=new Canvas(bitmap);
        d.setBounds(0, 0, width, height);
        d.draw(canvas);
        return bitmap;
	}
	public static Dialog getAlertDialog(Context context, 
			String str_title, String str_msg, String str_posivite, String str_negative,
			OnClickListener listener1, OnClickListener listener2)
	{
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(str_title);
		builder.setMessage(str_msg);
		builder.setPositiveButton(str_posivite, listener1);
		builder.setNegativeButton(str_negative, listener2);		
			
		Dialog dialog = builder.create();

		return dialog;
	}
	public static boolean isNewestVersion(Context context, int newestcode) {
		// TODO Auto-generated method stub
//		boolean result = false;
		try {
		    PackageManager packageManager = context.getPackageManager(); 
		    PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0); 
		    
			String version_name = packInfo.versionName;
			int version_code = packInfo.versionCode;

			LogUtil.e(TAG, "Version Name:" + version_name 
					+ " version Code:" + version_code
					+ "newestcode:" + newestcode);	
			
			if(version_code >= newestcode) {
				LogUtil.e(TAG, "is newest");
				return true;
			}
			
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LogUtil.ex(TAG, "", e);
			return false;
		}
	}
	public static void closeInput(Context context, EditText et){
		try{
			 InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
			 imm.hideSoftInputFromWindow(et.getWindowToken(), 0);			
		}catch(Exception e){
			LogUtil.ex(TAG, "", e);
		}
	}
	public static Drawable loadImageFromUrl(String url) {
//		LogUtil.e(TAG, "loadImageFromUrl:"+url);
		
		if(url.equals(""))
			return null;
		
//		url = url.replace("{0}", AppConfig.PIC_SIZE_3);
		URL mUrl;
		InputStream i = null;
		try {
			mUrl = new URL(url);
			i = (InputStream) mUrl.getContent();
//			LogUtil.e(TAG, "from net");
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			LogUtil.ex(TAG, "", e);
		}
		Drawable d = Drawable.createFromStream(i, "src");
		
		return d;
	}
    public static void showExitDialog(Context context) {
    	AlertDialog.Builder builder = new Builder(context);
    	builder.setMessage("确认退出吗？");

    	builder.setTitle("提示");

    	builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
    		@Override
  	  	   	public void onClick(DialogInterface dialog, int which)  {
  	  	    	dialog.dismiss();
  	  	    	android.os.Process.killProcess(android.os.Process.myPid());
  	  	   	}
    	});

    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    		@Override
  	  	   public void onClick(DialogInterface dialog, int which) {
  	  		   dialog.dismiss();
  	  	   }
    	});

    	builder.create().show();
  	}
    
    public static void installApk(Context context,String filename){
		File apkfile = new File(filename);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive"); 
        context.startActivity(i);
	}
    
    public static List<Address> getFromLocalName(Context context,String localname){
  	  Geocoder geocoded = new Geocoder(context, Locale.getDefault());
  	  try{		  
//  		GeoPoint geoBeijing = new GeoPoint(
//  				(int) (39.906033* 1000000),
//  				(int) (116.397700 * 1000000));
  		
  		List<Address> a = geocoded.getFromLocationName(localname, 1);
  		Address address = a.get(0);
  		
  		String str = address.getLatitude() + "" + address.getLongitude();		
  		LogUtil.e(TAG, "str:" + str + "address:" + a);
  		
  		return a;
  	  } 
  	  catch (Exception e){
  		 LogUtil.ex(TAG, "", e);
  		 return null;
  	  }
    }
}